package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.os.Handler;
import android.text.InputType;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.PackageCheckNumberAdapter;
import com.glory.dgcpcpda.adapter.PackageWoIDListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.EdcSetBinEntity;
import com.glory.dgcpcpda.entity.LotBindingVehicleEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PackageCheckNumberActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvCustomCode)
    TextView tvCustomCode;
    @BindView(R.id.tvPackageFrom)
    TextView tvPackageFrom;
    @BindView(R.id.tvPackNum)
    TextView tvPackNum;
    @BindView(R.id.etWoID)
    FreeUI_ClearEditText etWoID;
    @BindView(R.id.rvWoIDList)
    RecyclerView rvWoIDList;
    @BindView(R.id.etPackLabel)
    FreeUI_ClearEditText etPackLabel;
    @BindView(R.id.etPackLabelNum)
    FreeUI_ClearEditText etPackLabelNum;
    @BindView(R.id.tvGetData)
    TextView tvGetData;
    @BindView(R.id.tvGrade)
    TextView tvGrade;
    @BindView(R.id.rvStorageList)
    RecyclerView rvStorageList;
    @BindView(R.id.llPackLabelNum)
    LinearLayout llPackLabelNum;
    @BindView(R.id.llGetData)
    LinearLayout llGetData;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tvMainQty)
    TextView tvMainQty;
    @BindView(R.id.tvLable)
    TextView tvLable;
    private PackageCheckNumberAdapter mVehicleInfoAdapter;
    private PackageWoIDListAdapter suggestListAdapter;
    private ArrayList<String> woidList = new ArrayList<>();
    private int mainQty = 0;
    private Map<String, Integer> PackMap=new HashMap<>();
    private ArrayList<Map<String, Integer>> PackMap2 = new ArrayList<>();
    private String lotidsub = "";


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_package_checknumber;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView() {
        tvTitle.setText("测试卷盘数量校验");
        setMainLayout(llMain);
        initRecyclerView(rvStorageList,this);
        initRecyclerView(rvWoIDList,this);
        //卷盘标签列表
        mVehicleInfoAdapter = new PackageCheckNumberAdapter(null);
        mVehicleInfoAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mVehicleInfoAdapter.isFirstOnly(true);
        rvStorageList.setAdapter(mVehicleInfoAdapter);
        //订单列表
        suggestListAdapter = new PackageWoIDListAdapter(null);
        suggestListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        suggestListAdapter.isFirstOnly(true);
        rvWoIDList.setAdapter(suggestListAdapter);
        etPackLabelNum.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_SIGNED|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        clear();
        initEdit(etLot, s -> {
            clear();
            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                    (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                        LotInfoEntity lotinfo = response.body().getResponse().getBody();
                        if(lotinfo.getBASE_NUM().equals("")||lotinfo.getBASE_NUM().equals(null)){
                            showConfirmDialog(s+"卷盘数量为空");
                            return;
                        }
                        tvCustomCode.setText(lotinfo.getLOT().getCUSTOMERCODE());
                        tvPackageFrom.setText(lotinfo.getLOT().getMAINMATTYPE());
                        tvPackNum.setText(lotinfo.getBASE_NUM());
                        tvGrade.setText(lotinfo.getLOT().getGRADE1());
//                        tvMainQty.setText(lotinfo.getLOT().getMAINQTY());
                        mainQty=Integer.parseInt(lotinfo.getLOT().getMAINQTY());
                        if(!lotinfo.getMERGE_LOTS().equals(null)||!lotinfo.getMERGE_LOTS().equals("")){
                            if(lotinfo.getMERGE_LOTS().contains(",")){
                              String[] merge_lots= lotinfo.getMERGE_LOTS().split(",");
                              woidList.clear();
                              if(merge_lots.length>=1){
                                  for (int i=0;i<merge_lots.length;i++){
                                      if(!woidList.contains(merge_lots[i])){
                                          woidList.add(merge_lots[i]);
                                      }
                                  }
                              }
                            }
                        }
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(),"LOTQUERY");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE", "LOTQUERY");
            map.addProperty("PARENTFLAG", "Y");//MES根据此判断是否为主批
            map.addProperty("LOTID", s);
            NetUtils.requestPostNet("CPC.CHECKTESTREEL", "TRANSFERMES", this, map, callBack);
        });

        initEdit2(etPackLabel, s ->{
            String packlabel="";
            if(s.length()>11){
                if(s.contains("-")){
                   packlabel = s.split("-")[0]+"-1";
                }
                else{
                    showToast("标签"+s + "校验批次失败，请检查", false);
                    return;
                }
                if(!getText(etLot).contains(packlabel)){
                    showToast("标签"+s + "与批次"+getText(etLot)+"不匹配，请检查标签", false);
                    return;
                }
            }
            else{
                showToast("标签"+s + "校验批次失败，请检查", false);
                return;
            }
            int sum=0;
            if(mVehicleInfoAdapter.getData().size()>0) {
                for (LotBindingVehicleEntity sumentity : mVehicleInfoAdapter.getData()) {
//                    if (sumentity.getLotID().equals(s)) {
//                        showToast(s + "已扫描,请检查", false);
//                        etPackLabel.setText("");
//                        etPackLabel.setFocusable(true);
//                        etPackLabel.requestFocus();
//                        return;
//                    }
                    sum = sum + Integer.parseInt(sumentity.getVehicleCode());
                    if (sum + Integer.parseInt(tvPackNum.getText().toString()) > mainQty) {
                        llPackLabelNum.setVisibility(View.VISIBLE);
                        llGetData.setVisibility(View.VISIBLE);
                        etPackLabelNum.setFocusable(true);
                        new Handler().postDelayed(() -> etPackLabelNum.requestFocus(), 500);
                        return;
                    }
                }
            }
            else{
                if (Integer.parseInt(tvPackNum.getText().toString()) > mainQty) {
                    llPackLabelNum.setVisibility(View.VISIBLE);
                    llGetData.setVisibility(View.VISIBLE);
                    etPackLabelNum.setFocusable(true);
                    new Handler().postDelayed(() -> etPackLabelNum.requestFocus(), 500);
                    return;
                }
            }
            LotBindingVehicleEntity entity =new LotBindingVehicleEntity();
            entity.setLotID(s);
            entity.setVehicleCode(tvPackNum.getText().toString());
            mVehicleInfoAdapter.addData(entity);
            etPackLabel.setText("");
            etPackLabel.setFocusable(true);
            new Handler().postDelayed(() -> etPackLabel.requestFocus(), 500);
        });

        initEdit(etWoID, s ->{
            String lotid = s;
            if(s.length()>9){
                lotidsub = s.substring(0,9);
            }
            if(woidList.size()==0){
                showConfirmDialog("批次校验订单号内容为空，请检查是否合并订单");
                return;
            }
            if(woidList.contains(lotidsub)){
                if(suggestListAdapter.getData().contains(s)){
                    showToast(s+"已校验,请检查",true);
                    etWoID.setText("");
                    etWoID.requestFocus();
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                        (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            LotInfoEntity lotinfo = response.body().getResponse().getBody();
                            if(!lotinfo.getLOT().getGRADE1().equals(tvGrade.getText().toString()))
                            {
                                showConfirmDialog("合并批档位"+lotinfo.getLOT().getGRADE1()+"与主批档位"+tvGrade.getText().toString()+"不一致，不允许扫描");
                                return;
                            }
                            suggestListAdapter.addData(lotidsub);
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"LOTQUERY");
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "LOTQUERY");
                map.addProperty("LOTID", lotid);
                NetUtils.requestPostNet("CPC.CHECKTESTREEL", "TRANSFERMES", this, map, callBack);
            }else{
                showConfirmDialog("订单列表不包含"+lotidsub+",请检查");
            }
            etWoID.setText("");
            etWoID.setFocusable(true);
            new Handler().postDelayed(() -> etWoID.requestFocus(), 500);
        });
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit, R.id.tvGetData})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (actionControl("Submit43")) {
                    return;
                }
                if(woidList.size()>suggestListAdapter.getData().size()){
                    showToast("订单号没校验完不允许提交",false);
                    return;
                }
                if(mVehicleInfoAdapter.getData().size() == 0){
                    showToast("请扫描卷盘标签",false);
                    return;
                }
                request();
                break;
            case R.id.tvGetData:
                if(getText(etPackLabel).equals("")){
                    showToast("卷盘标签不能为空",false);
                    return;
                }
                if(getText(etPackLabelNum).equals("")){
                    showToast("尾数数量不能为空",false);
                    return;
                }

                String packlabel="";
                if(getText(etPackLabel).length()>11){
                    if(getText(etPackLabel).contains("-")){
                        packlabel = getText(etPackLabel).split("-")[0]+"-1";
                    }
                    else{
                        showToast("标签"+getText(etPackLabel) + "校验批次失败，请检查", false);
                        return;
                    }
                    if(!getText(etLot).contains(packlabel)){
                        showToast("标签"+getText(etPackLabel) + "与批次"+getText(etLot)+"不匹配，请检查标签", false);
                        return;
                    }
                }
                else{
                    showToast("标签"+getText(etPackLabel) + "校验批次失败，请检查", false);
                    return;
                }
                LotBindingVehicleEntity entity =new LotBindingVehicleEntity();
                entity.setLotID(getText(etPackLabel));
                entity.setVehicleCode(getText(etPackLabelNum));
                mVehicleInfoAdapter.addData(entity);
                etPackLabel.setText("");
                etPackLabelNum.setText("");
                llPackLabelNum.setVisibility(View.GONE);
                llGetData.setVisibility(View.GONE);
                break;
        }
    }

    private  void request(){
        FreeUI_EntityCallBack<BaseResponseBean<EdcSetBinEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcSetBinEntity>>
                (new TypeToken<BaseResponseBean<EdcSetBinEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EdcSetBinEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    clear();
                    EdcSetBinEntity edcSetBinEntity = response.body().getResponse().getBody();
                    if(edcSetBinEntity.getCOMMENT().equals("")){
                        showConfirmDialog("提交成功");
                    }
                    else {
                        showConfirmDialog(edcSetBinEntity.getCOMMENT());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcSetBinEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"TRANSFERMES");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "TESTREELCHECKDATA");
        map.addProperty("LOTID", etLot.getText().toString());
        map.addProperty("REELNUM", Integer.parseInt(tvPackNum.getText().toString()));
        int qty = 0;
        if(mVehicleInfoAdapter.getData().size()>0){
            for(LotBindingVehicleEntity sumentity:mVehicleInfoAdapter.getData()){
                PackMap.put(sumentity.getLotID(),Integer.parseInt(sumentity.getVehicleCode()));
                PackMap2.add(new HashMap<>(PackMap));
                qty = qty + Integer.parseInt(sumentity.getVehicleCode());
            }
        }
        map.addProperty("LABELSUMQTY", qty);
        map.add("LABELMAP", new JsonParser().parse(new Gson().toJson(PackMap2)).getAsJsonArray());
        NetUtils.requestPostNet("CPC.CHECKTESTREEL", "TRANSFERMES", this, map, callBack);
    }

    private void clear(){
        tvCustomCode.setText("");
        tvPackageFrom.setText("");
        tvPackNum.setText("");
        tvGrade.setText("");
        tvMainQty.setText("");
        suggestListAdapter.getData().clear();
        suggestListAdapter.notifyDataSetChanged();
        mVehicleInfoAdapter.getData().clear();
        mVehicleInfoAdapter.notifyDataSetChanged();
        woidList.clear();
        PackMap.clear();
        PackMap2.clear();
    }
}
